package cn.tedu.boot23.controller;

import cn.tedu.boot23.entity.Hero;
import cn.tedu.boot23.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;

@Controller
public class HeroController {
    @ResponseBody
    @RequestMapping("/add")
    public String add(Hero hero){
        System.out.println("hero = " + hero);
        try(Connection conn= DBUtils.getCoon()) {

            String sql="insert into hero value(null,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,hero.getName());
            ps.setString(2,hero.getType());
            ps.setDouble(3,hero.getMoney());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加成功";
    }
    @ResponseBody
    @RequestMapping("/select")
    public String select(Hero hero){
        String html="<table border=1>";
        html+="<caption>英雄列表</caption>";
        html+="<tr><th>id</th><th>英雄名</th><th>能力类型</th><th>小金库</th></tr>";
        try ( Connection conn=DBUtils.getCoon()){
            String sql="select id,name,type,money from hero";
            Statement s=conn.createStatement();
            ResultSet rs=s.executeQuery(sql);
            while (rs.next()){
                int id=rs.getInt(1);
                String name=rs.getString(2);
                String type=rs.getString(3);
                double money=rs.getDouble(4);
                html+="<tr>";
                html+="<td>"+id+"</td>";
                html+="<td>"+name+"</td>";
                html+="<td>"+type+"</td>";
                html+="<td>"+money+"</td>";
                html+="</tr>";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        html+="</table>";
        return html;
    }
}
